# zennotac-backend/app/jobs/cleanup_job.py
import os
import shutil
from datetime import datetime
from app.config.base_setting import (
    UPLOAD_FOLDER,
    OCR_OUTPUT_FOLDER,
    ARCHIVE_UPLOAD_FOLDER,
    ARCHIVE_OCR_OUTPUT_FOLDER,
    backend_logger,
)

def archive_files(source_folder, target_folder, description=""):
    backend_logger.info(f"[ARCHIVE] Moving files from {description} ({source_folder}) -> {target_folder}")
    for fname in os.listdir(source_folder):
        src = os.path.join(source_folder, fname)
        dst = os.path.join(target_folder, fname)

        try:
            if os.path.isfile(src):
                shutil.move(src, dst)
                backend_logger.info(f"[ARCHIVE] Moved {description}: {fname}")
        except Exception as e:
            backend_logger.exception(f"[ARCHIVE] Failed to move {description} file {fname}: {e}")

def cleanup_old_files(folder, max_days=30, max_file_size_mb=1024, description=""):
    backend_logger.info(f"[CLEANUP] Checking {description} for stale files...")
    now = datetime.now()
    max_size_bytes = max_file_size_mb * 1024 * 1024
    deleted = 0

    for fname in os.listdir(folder):
        fpath = os.path.join(folder, fname)
        try:
            if os.path.isfile(fpath):
                age_days = (now - datetime.fromtimestamp(os.path.getmtime(fpath))).days
                size = os.path.getsize(fpath)
                if age_days > max_days or size > max_size_bytes:
                    os.remove(fpath)
                    backend_logger.info(f"[CLEANUP] Deleted {description}: {fname} (age: {age_days}d, size: {size}B)")
                    deleted += 1
        except Exception as e:
            backend_logger.exception(f"[CLEANUP] Error deleting {description} file {fname}: {e}")
    
    backend_logger.info(f"[CLEANUP] Completed. Total deleted from {description}: {deleted}")


def run_daily_archive_and_cleanup():
    # Archive freshly ocred data
    archive_files(UPLOAD_FOLDER, ARCHIVE_UPLOAD_FOLDER, "UPLOAD")
    archive_files(OCR_OUTPUT_FOLDER, ARCHIVE_OCR_OUTPUT_FOLDER, "OCRED")

    # Delete old files from archive folders
    cleanup_old_files(ARCHIVE_UPLOAD_FOLDER, max_days=30, description="ARCHIVE_UPLOAD")
    cleanup_old_files(ARCHIVE_OCR_OUTPUT_FOLDER, max_days=30, description="ARCHIVE_OCRED")
